package com.chuantou.yuba.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.chuantou.yuba.R;
import com.chuantou.yuba.ui.widget.GalleryViewPager;
import com.chuantou.yuba.ui.widget.TouchImageView;
import com.chuantou.yuba.util.BitmapBinder;

public class GalleryActivity extends BaseActionBarActivity implements OnClickListener {

	public static final String EXTRA_DATA = "data";
	public static final String EXTRA_INDEX = "index";
	private GalleryViewPager mViewPager;
	private TextView mCountTxt;
	private List<String> mImages;
	private GalleryAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar actionBar = getSupportActionBar();
		if (actionBar != null) {
			try {
				actionBar.hide();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mImages = getIntent().getStringArrayListExtra(EXTRA_DATA);
		setContentView(R.layout.galley);
		setupViews();
	}

	private void setupViews() {
		mViewPager = (GalleryViewPager) findViewById(R.id.viewpager);
		mCountTxt = (TextView) findViewById(R.id.count);
		mViewPager.setOffscreenPageLimit(1);
		mAdapter = new GalleryAdapter(getApplicationContext());
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(mPageChangeListener);
		int index = getIntent().getIntExtra(EXTRA_INDEX, 0);
		if (index > 0 && index < mAdapter.getCount()) {
			mViewPager.setCurrentItem(index);
			setCountText(index + 1, mAdapter.getCount());
		}else{
			mCountTxt.setVisibility(View.GONE);
		}
	}

	OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int position) {
			setCountText(position + 1, mAdapter.getCount());
		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

		}

		@Override
		public void onPageScrollStateChanged(int state) {

		}
	};

	private void setCountText(int currentIndex, int total) {
		mCountTxt.setText(String.format("%d/%d", currentIndex, total));
	}

	class GalleryAdapter extends PagerAdapter {

		protected final Context mContext;
		protected int mCurrentPosition = -1;
		private int mScreenWidth;
		private int mScreenHeight;

		public GalleryAdapter(Context context) {
			this.mContext = context;
			DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
			mScreenWidth = metrics.widthPixels;
			mScreenHeight = metrics.heightPixels;
		}

		@Override
		public void setPrimaryItem(ViewGroup container, final int position, Object object) {
			super.setPrimaryItem(container, position, object);
			if (mCurrentPosition == position)
				return;
			GalleryViewPager galleryContainer = (GalleryViewPager) container;
			if (galleryContainer.getTouchImageView() != null) {
				galleryContainer.getTouchImageView().resetScale();
			}
			View v = (View) object;
			TouchImageView imageView = (TouchImageView) v.findViewById(R.id.image);
			galleryContainer.setTouchImageView(imageView);
			mCurrentPosition = position;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View contentView = inflater.inflate(R.layout.gallery_item, null);
			final TouchImageView imageView = (TouchImageView) contentView.findViewById(R.id.image);
			imageView.setOnClickListener(GalleryActivity.this);
			final ProgressBar progressBar = (ProgressBar) contentView.findViewById(R.id.progressbar);
			imageView.setScaleType(ScaleType.CENTER_INSIDE);
			imageView.setImageResource(R.drawable.default_image_big);
			progressBar.setVisibility(View.VISIBLE);
			if (!TextUtils.isEmpty(mImages.get(position))) {
				BitmapBinder.getImageLoader(mContext).get(mImages.get(position), new ImageListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						imageView.setScaleType(ScaleType.CENTER_INSIDE);
						imageView.setImageResource(R.drawable.default_image_big);
						progressBar.setVisibility(View.GONE);
					}

					@Override
					public void onResponse(ImageContainer response, boolean isImmediate) {
						if (response != null && response.getBitmap() == null) {
							imageView.setScaleType(ScaleType.CENTER_INSIDE);
							imageView.setImageResource(R.drawable.default_image_big);
						} else {
							progressBar.setVisibility(View.GONE);
							imageView.setScaleType(ScaleType.MATRIX);
							imageView.setImageBitmap(response.getBitmap());
						}
					}
				}, mScreenWidth, mScreenHeight, null);
			}
			container.addView(contentView);
			return contentView;
		}

		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			collection.removeView((View) view);
		}

		@Override
		public int getCount() {
			return mImages == null ? 0 : mImages.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		public int getCurrentPosition() {
			return mCurrentPosition;
		}
	}

	public static void start(Context context, ArrayList<String> images, int index) {
		Intent intent = new Intent(context, GalleryActivity.class);
		intent.putStringArrayListExtra(EXTRA_DATA, images);
		intent.putExtra(EXTRA_INDEX, index);
		if (!(context instanceof Activity)) {
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}
		context.startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		finish();
	}

}
